﻿using System;
using System.Collections;

namespace Eneta.Portal.Forum.Common.Data
{
    public class SharePointListItem
    {
        // Fields
        private Hashtable _fieldIndexes;
        private SharePointListField[] _sharePointListFields;

        // Methods
        public SharePointListItem()
        {
            _sharePointListFields = new SharePointListField[0];
        }

        public SharePointListItem(int id, params string[] values)
        {
            _sharePointListFields = new SharePointListField[0];
            var index = 0;
            Id = id;
            while (index < values.Length)
            {
                Add(values[index], values[index + 1], false);
                index += 2;
            }
        }

        public void Add(string name, string fieldValue, bool readOnly)
        {
            var list = new ArrayList(SharePointListFields)
                           {
                               new SharePointListField(name, fieldValue, readOnly)
                           };
            _sharePointListFields = new SharePointListField[list.Count];
            list.CopyTo(SharePointListFields);
        }

        private void InitFieldIndexes()
        {
            _fieldIndexes = new Hashtable();
            _fieldIndexes.Clear();
            foreach (var field in SharePointListFields)
            {
                if (!_fieldIndexes.ContainsKey(field.Name))
                {
                    _fieldIndexes.Add(field.Name, field);
                }
            }
        }

        // Properties
        public int Id { get; set; }

        public string this[string name]
        {
            get
            {
                if (_fieldIndexes == null)
                {
                    InitFieldIndexes();
                }
                if (_fieldIndexes.ContainsKey(name))
                {
                    return ((SharePointListField)_fieldIndexes[name]).Value;
                }
                return null;
            }
            set
            {
                if (_fieldIndexes == null)
                {
                    InitFieldIndexes();
                }
                if (!_fieldIndexes.ContainsKey(name))
                {
                    throw new IndexOutOfRangeException();
                }
                ((SharePointListField)_fieldIndexes[name]).Value = value;
            }
        }

        public SharePointListField[] SharePointListFields
        {
            get
            {
                return _sharePointListFields;
            }
            set
            {
                _sharePointListFields = value;
            }
        }
    }
}
